package reflection;

/*
 * Author: JacksonCoder
 * FileName: reflectionExample
 * Version: 1.0.0
 */

import java.lang.reflect.Field;
import java.lang.reflect.Method;

class Person {
    private String name;

    private int age;

    // constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    //
    public void greet(String message) {
        System.out.println(name + " says: " + message);
    }

    private void secretMethod() {
        System.out.println("This is a secret message");
    }

}

public class reflectionExample {

    public static void main(String[] args) throws Exception {
        //1 获取class 对象
        Class<?> clazz = Person.class;

        //2. 创建对象实例
        Person person = (Person) clazz.getDeclaredConstructor(String.class, int.class)
                .newInstance("JacksonCoder", 18);


        // 3. 动态调用公共方法
        Method greetMethod = clazz.getMethod("greet", String.class);
        greetMethod.invoke(person, "Hello, World!");

        // 4 访问私有变量
        Field nameField = clazz.getDeclaredField("name");
        nameField.setAccessible(true); // 绕过访问权限
        System.out.println("Before change: " + nameField.get(person));
        nameField.set(person, "Bob");
        System.out.println("After change: " + nameField.get(person));

        // 5. 调用私有方法
        Method secretMethod = clazz.getDeclaredMethod("secretMethod");
        secretMethod.setAccessible(true); // 绕过访问权限
        secretMethod.invoke(person);
    }

}
